﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace Traceability.APP.Controllers
{
    /// <summary>
    /// Api 控制器-图片管理
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class ImgController : ControllerBase
    {

        /// <summary>
        /// 图片上传
        /// </summary>
        /// <param name="file">图片文件</param>
        /// <returns>返回符合条件的数据</returns>
        [HttpPost]
        public IActionResult Imgs(IFormFile file)
        {
            try
            {
                //1.判断上传的文件格式
                //获取文件格式
                var t = file.ContentType;
                List<string> ts = new List<string>
                {
                    "image/png",
                    "image/jpg",
                    "image/jpeg",
                    "image/webp",
                    "image/gif"
                };
                if (!ts.Contains(t))
                {
                    return Ok("不是图片");
                }

                //2.判断一图片的大小 要求不要大于2M   b  kb  mb  gb  tb  1024
                var max = 1024 * 1024 * 2;
                if (file.Length > max)
                {
                    return Ok("大于2M");
                }

                //3.实现图片上传
                var p = Directory.GetCurrentDirectory() + @"/wwwroot/Pic/" + file.FileName;

                using (FileStream fs = new FileStream(p, FileMode.Create))
                {
                    file.CopyTo(fs);
                    fs.Flush();
                }

                return Ok("http://localhost:5091/Pic/" + file.FileName);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

    }
}
